[[...path]].page.tsx 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. import React, { useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import {
  4. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision, isClient, isIPageInfoForEntity, IUser, IUserHasId, pagePathUtils, pathUtils,
  5. } from '@growi/core';
  6. import ExtensibleCustomError from 'extensible-custom-error';
  7. import { model as mongooseModel } from 'mongoose';
  8. import {
  9. NextPage, GetServerSideProps, GetServerSidePropsContext,
  10. } from 'next';
  11. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  12. import dynamic from 'next/dynamic';
  13. import Head from 'next/head';
  14. import { useRouter } from 'next/router';
  15. import superjson from 'superjson';
  16. import { Comments } from '~/components/Comments';
  17. import { PageAlerts } from '~/components/PageAlert/PageAlerts';
  18. // import { useTranslation } from '~/i18n';
  19. import { CurrentPageContentFooter } from '~/components/PageContentFooter';
  20. import { UsersHomePageFooterProps } from '~/components/UsersHomePageFooter';
  21. import { CrowiRequest } from '~/interfaces/crowi-request';
  22. // import { renderScriptTagByName, renderHighlightJsStyleTag } from '~/service/cdn-resources-loader';
  23. // import { useIndentSize } from '~/stores/editor';
  24. // import { useRendererSettings } from '~/stores/renderer';
  25. // import { EditorMode, useEditorMode, useIsMobile } from '~/stores/ui';
  26. import { EditorConfig } from '~/interfaces/editor-settings';
  27. import { CustomWindow } from '~/interfaces/global';
  28. import { RendererConfig } from '~/interfaces/services/renderer';
  29. import { ISidebarConfig } from '~/interfaces/sidebar-config';
  30. import { IUserUISettings } from '~/interfaces/user-ui-settings';
  31. import { PageModel, PageDocument } from '~/server/models/page';
  32. import { PageRedirectModel } from '~/server/models/page-redirect';
  33. import { UserUISettingsModel } from '~/server/models/user-ui-settings';
  34. import { useSWRxCurrentPage, useSWRxIsGrantNormalized } from '~/stores/page';
  35. import { useRedirectFrom } from '~/stores/page-redirect';
  36. import {
  37. usePreferDrawerModeByUser, usePreferDrawerModeOnEditByUser, useSidebarCollapsed, useCurrentSidebarContents, useCurrentProductNavWidth, useSelectedGrant,
  38. } from '~/stores/ui';
  39. import loggerFactory from '~/utils/logger';
  40. // import { isUserPage, isTrashPage, isSharedPage } from '~/utils/path-utils';
  41. // import GrowiSubNavigation from '../client/js/components/Navbar/GrowiSubNavigation';
  42. // import GrowiSubNavigationSwitcher from '../client/js/components/Navbar/GrowiSubNavigationSwitcher';
  43. import { DescendantsPageListModal } from '../components/DescendantsPageListModal';
  44. import { BasicLayout } from '../components/Layout/BasicLayout';
  45. import GrowiContextualSubNavigation from '../components/Navbar/GrowiContextualSubNavigation';
  46. import DisplaySwitcher from '../components/Page/DisplaySwitcher';
  47. // import { serializeUserSecurely } from '../server/models/serializers/user-serializer';
  48. // import PageStatusAlert from '../client/js/components/PageStatusAlert';
  49. import {
  50. useCurrentUser, useCurrentPagePath,
  51. useIsLatestRevision,
  52. useIsForbidden, useIsNotFound, useIsTrashPage, useIsSharedUser,
  53. useIsEnabledStaleNotification, useIsIdenticalPath,
  54. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  55. useHackmdUri,
  56. useIsAclEnabled, useIsUserPage,
  57. useCsrfToken, useIsSearchScopeChildrenAsDefault, useCurrentPageId, useCurrentPathname,
  58. useIsSlackConfigured, useRendererConfig, useEditingMarkdown,
  59. useEditorConfig, useIsAllReplyShown, useIsUploadableFile, useIsUploadableImage, usePageUser,
  60. } from '../stores/context';
  61. import {
  62. CommonProps, getNextI18NextConfig, getServerSideCommonProps, useCustomTitle,
  63. } from './utils/commons';
  64. // import { useCurrentPageSWR } from '../stores/page';
  65. const NotCreatablePage = dynamic(() => import('../components/NotCreatablePage').then(mod => mod.NotCreatablePage), { ssr: false });
  66. const ForbiddenPage = dynamic(() => import('../components/ForbiddenPage'), { ssr: false });
  67. const UnsavedAlertDialog = dynamic(() => import('./UnsavedAlertDialog'), { ssr: false });
  68. const GrowiSubNavigationSwitcher = dynamic(() => import('../components/Navbar/GrowiSubNavigationSwitcher'), { ssr: false });
  69. const UsersHomePageFooter = dynamic<UsersHomePageFooterProps>(() => import('../components/UsersHomePageFooter')
  70. .then(mod => mod.UsersHomePageFooter), { ssr: false });
  71. const logger = loggerFactory('growi:pages:all');
  72. const {
  73. isPermalink: _isPermalink, isUsersHomePage, isTrashPage: _isTrashPage, isUserPage, isCreatablePage, isTopPage,
  74. } = pagePathUtils;
  75. const { removeHeadingSlash } = pathUtils;
  76. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  77. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  78. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  79. {
  80. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  81. return v?.data != null
  82. && v?.data.toObject != null
  83. && v?.meta != null
  84. && isIPageInfoForEntity(v.meta);
  85. },
  86. serialize: (v) => {
  87. return {
  88. data: superjson.stringify(v.data.toObject()),
  89. meta: superjson.stringify(v.meta),
  90. };
  91. },
  92. deserialize: (v) => {
  93. return {
  94. data: superjson.parse(v.data),
  95. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  96. };
  97. },
  98. },
  99. 'IPageToShowRevisionWithMetaTransformer',
  100. );
  101. const IdenticalPathPage = (): JSX.Element => {
  102. const IdenticalPathPage = dynamic(() => import('../components/IdenticalPathPage').then(mod => mod.IdenticalPathPage), { ssr: false });
  103. return <IdenticalPathPage />;
  104. };
  105. const PutbackPageModal = (): JSX.Element => {
  106. const PutbackPageModal = dynamic(() => import('../components/PutbackPageModal'), { ssr: false });
  107. return <PutbackPageModal />;
  108. };
  109. type Props = CommonProps & {
  110. currentUser: IUser,
  111. pageWithMeta: IPageToShowRevisionWithMeta,
  112. // pageUser?: any,
  113. redirectFrom?: string;
  114. // shareLinkId?: string;
  115. isLatestRevision?: boolean
  116. isIdenticalPathPage?: boolean,
  117. isForbidden: boolean,
  118. isNotFound: boolean,
  119. isNotCreatablePage: boolean,
  120. // isAbleToDeleteCompletely: boolean,
  121. isSearchServiceConfigured: boolean,
  122. isSearchServiceReachable: boolean,
  123. isSearchScopeChildrenAsDefault: boolean,
  124. isSlackConfigured: boolean,
  125. // isMailerSetup: boolean,
  126. isAclEnabled: boolean,
  127. // hasSlackConfig: boolean,
  128. // drawioUri: string,
  129. hackmdUri: string,
  130. // noCdn: string,
  131. // highlightJsStyle: string,
  132. isAllReplyShown: boolean,
  133. // isContainerFluid: boolean,
  134. editorConfig: EditorConfig,
  135. isEnabledStaleNotification: boolean,
  136. // isEnabledLinebreaks: boolean,
  137. // isEnabledLinebreaksInComments: boolean,
  138. // adminPreferredIndentSize: number,
  139. // isIndentSizeForced: boolean,
  140. disableLinkSharing: boolean,
  141. rendererConfig: RendererConfig,
  142. // UI
  143. userUISettings?: IUserUISettings
  144. // Sidebar
  145. sidebarConfig: ISidebarConfig,
  146. };
  147. const GrowiPage: NextPage<Props> = (props: Props) => {
  148. // const { t } = useTranslation();
  149. const router = useRouter();
  150. const { data: currentUser } = useCurrentUser(props.currentUser ?? null);
  151. // register global EventEmitter
  152. if (isClient()) {
  153. (window as CustomWindow).globalEmitter = new EventEmitter();
  154. }
  155. // commons
  156. useEditorConfig(props.editorConfig);
  157. useCsrfToken(props.csrfToken);
  158. // UserUISettings
  159. usePreferDrawerModeByUser(props.userUISettings?.preferDrawerModeByUser ?? props.sidebarConfig.isSidebarDrawerMode);
  160. usePreferDrawerModeOnEditByUser(props.userUISettings?.preferDrawerModeOnEditByUser);
  161. useSidebarCollapsed(props.userUISettings?.isSidebarCollapsed ?? props.sidebarConfig.isSidebarClosedAtDockMode);
  162. useCurrentSidebarContents(props.userUISettings?.currentSidebarContents);
  163. useCurrentProductNavWidth(props.userUISettings?.currentProductNavWidth);
  164. // page
  165. useIsLatestRevision(props.isLatestRevision);
  166. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  167. useIsForbidden(props.isForbidden);
  168. useIsNotFound(props.isNotFound);
  169. // useIsNotCreatable(props.IsNotCreatable);
  170. useRedirectFrom(props.redirectFrom);
  171. // useShared();
  172. // useShareLinkId(props.shareLinkId);
  173. useIsSharedUser(false); // this page cann't be routed for '/share'
  174. useIsIdenticalPath(false); // TODO: need to initialize from props
  175. // useIsAbleToDeleteCompletely(props.isAbleToDeleteCompletely);
  176. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  177. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  178. useIsSearchServiceReachable(props.isSearchServiceReachable);
  179. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  180. useIsSlackConfigured(props.isSlackConfigured);
  181. // useIsMailerSetup(props.isMailerSetup);
  182. useIsAclEnabled(props.isAclEnabled);
  183. // useHasSlackConfig(props.hasSlackConfig);
  184. // useDrawioUri(props.drawioUri);
  185. useHackmdUri(props.hackmdUri);
  186. // useNoCdn(props.noCdn);
  187. // useIndentSize(props.adminPreferredIndentSize);
  188. useDisableLinkSharing(props.disableLinkSharing);
  189. useRendererConfig(props.rendererConfig);
  190. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  191. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  192. useIsAllReplyShown(props.isAllReplyShown);
  193. useIsUploadableFile(props.editorConfig.upload.isUploadableFile);
  194. useIsUploadableImage(props.editorConfig.upload.isUploadableImage);
  195. // const { data: editorMode } = useEditorMode();
  196. const { pageWithMeta, userUISettings } = props;
  197. let shouldRenderPutbackPageModal = false;
  198. if (pageWithMeta != null) {
  199. shouldRenderPutbackPageModal = _isTrashPage(pageWithMeta.data.path);
  200. }
  201. const pageId = pageWithMeta?.data._id;
  202. const pagePath = pageWithMeta?.data.path ?? props.currentPathname;
  203. useCurrentPageId(pageId);
  204. useSWRxCurrentPage(undefined, pageWithMeta?.data); // store initial data
  205. useIsUserPage(isUserPage(pagePath));
  206. // useIsNotCreatable(props.isForbidden || !isCreatablePage(pagePath)); // TODO: need to include props.isIdentical
  207. useCurrentPagePath(pagePath);
  208. useCurrentPathname(props.currentPathname);
  209. useEditingMarkdown(pageWithMeta?.data.revision?.body);
  210. useIsTrashPage(_isTrashPage(pagePath));
  211. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  212. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  213. usePageUser(pageWithMeta?.data.creator);
  214. // sync grant data
  215. useEffect(() => {
  216. mutateSelectedGrant(grantData?.grantData.currentPageGrant);
  217. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant]);
  218. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  219. useEffect(() => {
  220. const decodedURI = decodeURI(window.location.pathname);
  221. if (isClient() && decodedURI !== props.currentPathname) {
  222. router.replace(props.currentPathname, undefined, { shallow: true });
  223. }
  224. }, [props.currentPathname, router]);
  225. const classNames: string[] = [];
  226. // switch (editorMode) {
  227. // case EditorMode.Editor:
  228. // classNames.push('on-edit', 'builtin-editor');
  229. // break;
  230. // case EditorMode.HackMD:
  231. // classNames.push('on-edit', 'hackmd');
  232. // break;
  233. // }
  234. // if (page == null) {
  235. // classNames.push('not-found-page');
  236. // }
  237. const isTopPagePath = isTopPage(pageWithMeta?.data.path ?? '');
  238. return (
  239. <>
  240. <Head>
  241. {/*
  242. {renderScriptTagByName('drawio-viewer')}
  243. {renderScriptTagByName('highlight-addons')}
  244. {renderHighlightJsStyleTag(props.highlightJsStyle)}
  245. */}
  246. </Head>
  247. {/* <BasicLayout title={useCustomTitle(props, t('GROWI'))} className={classNames.join(' ')}> */}
  248. <BasicLayout title={useCustomTitle(props, 'GROWI')} className={classNames.join(' ')} expandContainer={props.isContainerFluid}>
  249. <div className="h-100 d-flex flex-column justify-content-between">
  250. <header className="py-0 position-relative">
  251. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  252. </header>
  253. <div className="d-edit-none">
  254. <GrowiSubNavigationSwitcher />
  255. </div>
  256. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  257. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  258. <div className="flex-grow-1">
  259. <div id="main" className={`main ${isUsersHomePage(props.currentPathname) && 'user-page'}`}>
  260. <div id="content-main" className="content-main grw-container-convertible">
  261. { props.isIdenticalPathPage && <IdenticalPathPage /> }
  262. { !props.isIdenticalPathPage && (
  263. <>
  264. <PageAlerts />
  265. { props.isForbidden && <ForbiddenPage /> }
  266. { props.isNotCreatablePage && <NotCreatablePage />}
  267. { !props.isForbidden && !props.isNotCreatablePage && <DisplaySwitcher />}
  268. {/* <DisplaySwitcher /> */}
  269. {/* <PageStatusAlert /> */}
  270. </>
  271. ) }
  272. {/* <div className="col-xl-2 col-lg-3 d-none d-lg-block revision-toc-container">
  273. <div id="revision-toc" className="revision-toc mt-3 sps sps--abv" data-sps-offset="123">
  274. <div id="revision-toc-content" className="revision-toc-content"></div>
  275. </div>
  276. </div> */}
  277. </div>
  278. </div>
  279. </div>
  280. { !props.isIdenticalPathPage && !props.isNotFound && (
  281. <footer className="footer d-edit-none">
  282. { !isTopPagePath && (<Comments pageId={pageId} revision={pageWithMeta?.data.revision} />) }
  283. { (pageWithMeta != null && isUsersHomePage(pageWithMeta.data.path)) && (
  284. <UsersHomePageFooter creatorId={pageWithMeta.data.creator._id}/>
  285. ) }
  286. <CurrentPageContentFooter />
  287. </footer>
  288. )}
  289. <UnsavedAlertDialog />
  290. <DescendantsPageListModal />
  291. {shouldRenderPutbackPageModal && <PutbackPageModal />}
  292. </div>
  293. </BasicLayout>
  294. </>
  295. );
  296. };
  297. function getPageIdFromPathname(currentPathname: string): string | null {
  298. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  299. }
  300. class MultiplePagesHitsError extends ExtensibleCustomError {
  301. pagePath: string;
  302. constructor(pagePath: string) {
  303. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  304. this.pagePath = pagePath;
  305. }
  306. }
  307. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  308. const req: CrowiRequest = context.req as CrowiRequest;
  309. const { crowi } = req;
  310. const { revisionId } = req.query;
  311. const Page = crowi.model('Page') as PageModel;
  312. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  313. const { pageService } = crowi;
  314. let currentPathname = props.currentPathname;
  315. const pageId = getPageIdFromPathname(currentPathname);
  316. const isPermalink = _isPermalink(currentPathname);
  317. const { user } = req;
  318. if (!isPermalink) {
  319. // check redirects
  320. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  321. if (chains != null) {
  322. // overwrite currentPathname
  323. currentPathname = chains.end.toPath;
  324. props.currentPathname = currentPathname;
  325. // set redirectFrom
  326. props.redirectFrom = chains.start.fromPath;
  327. }
  328. // check whether the specified page path hits to multiple pages
  329. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  330. if (count > 1) {
  331. throw new MultiplePagesHitsError(currentPathname);
  332. }
  333. }
  334. const pageWithMeta: IPageToShowRevisionWithMeta = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  335. const page = pageWithMeta?.data as unknown as PageDocument;
  336. // add user to seen users
  337. if (page != null && user != null) {
  338. await page.seen(user);
  339. }
  340. // populate & check if the revision is latest
  341. if (page != null) {
  342. page.initLatestRevisionField(revisionId);
  343. await page.populateDataToShowRevision();
  344. props.isLatestRevision = page.isLatestRevision();
  345. }
  346. props.pageWithMeta = pageWithMeta;
  347. }
  348. async function injectUserUISettings(context: GetServerSidePropsContext, props: Props): Promise<void> {
  349. const req = context.req as CrowiRequest<IUserHasId & any>;
  350. const { user } = req;
  351. const UserUISettings = mongooseModel('UserUISettings') as UserUISettingsModel;
  352. const userUISettings = user == null ? null : await UserUISettings.findOne({ user: user._id }).exec();
  353. if (userUISettings != null) {
  354. props.userUISettings = userUISettings.toObject();
  355. }
  356. }
  357. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  358. const req: CrowiRequest = context.req as CrowiRequest;
  359. const { crowi } = req;
  360. const Page = crowi.model('Page') as PageModel;
  361. const { currentPathname } = props;
  362. const pageId = getPageIdFromPathname(currentPathname);
  363. const isPermalink = _isPermalink(currentPathname);
  364. const page = props.pageWithMeta?.data;
  365. if (props.isIdenticalPathPage) {
  366. // TBD
  367. }
  368. else if (page == null) {
  369. props.isNotFound = true;
  370. props.isNotCreatablePage = !isCreatablePage(currentPathname);
  371. // check the page is forbidden or just does not exist.
  372. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  373. props.isForbidden = count > 0;
  374. }
  375. else {
  376. props.isNotFound = page.isEmpty;
  377. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  378. if (isPermalink && page.isEmpty) {
  379. props.currentPathname = page.path;
  380. }
  381. // /path/to/page ==> /62a88db47fed8b2d94f30000
  382. if (!isPermalink && !page.isEmpty) {
  383. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  384. if (!isToppage) {
  385. props.currentPathname = `/${page._id}`;
  386. }
  387. }
  388. }
  389. }
  390. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  391. // const req: CrowiRequest = context.req as CrowiRequest;
  392. // const { crowi } = req;
  393. // const UserModel = crowi.model('User');
  394. // if (isUserPage(props.currentPagePath)) {
  395. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  396. // if (user != null) {
  397. // props.pageUser = JSON.stringify(user.toObject());
  398. // }
  399. // }
  400. // }
  401. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  402. const req: CrowiRequest = context.req as CrowiRequest;
  403. const { crowi } = req;
  404. const {
  405. appService, searchService, configManager, aclService, slackNotificationService, mailService,
  406. } = crowi;
  407. props.isSearchServiceConfigured = searchService.isConfigured;
  408. props.isSearchServiceReachable = searchService.isReachable;
  409. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  410. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  411. // props.isMailerSetup = mailService.isMailerSetup;
  412. props.isAclEnabled = aclService.isAclEnabled();
  413. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  414. // props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  415. props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  416. // props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  417. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  418. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  419. // props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  420. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  421. // props.isEnabledLinebreaks = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks');
  422. // props.isEnabledLinebreaksInComments = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments');
  423. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  424. props.editorConfig = {
  425. upload: {
  426. isUploadableFile: crowi.fileUploadService.getFileUploadEnabled(),
  427. isUploadableImage: crowi.fileUploadService.getIsUploadable(),
  428. },
  429. };
  430. // props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  431. // props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  432. props.rendererConfig = {
  433. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  434. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  435. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  436. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  437. plantumlUri: process.env.PLANTUML_URI ?? null,
  438. blockdiagUri: process.env.BLOCKDIAG_URI ?? null,
  439. // XSS Options
  440. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:xss:isEnabledPrevention'),
  441. attrWhiteList: crowi.xssService.getAttrWhiteList(),
  442. tagWhiteList: crowi.xssService.getTagWhiteList(),
  443. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  444. };
  445. props.sidebarConfig = {
  446. isSidebarDrawerMode: configManager.getConfig('crowi', 'customize:isSidebarDrawerMode'),
  447. isSidebarClosedAtDockMode: configManager.getConfig('crowi', 'customize:isSidebarClosedAtDockMode'),
  448. };
  449. }
  450. /**
  451. * for Server Side Translations
  452. * @param context
  453. * @param props
  454. * @param namespacesRequired
  455. */
  456. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  457. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  458. props._nextI18Next = nextI18NextConfig._nextI18Next;
  459. }
  460. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  461. const req = context.req as CrowiRequest<IUserHasId & any>;
  462. const { user } = req;
  463. const result = await getServerSideCommonProps(context);
  464. // check for presence
  465. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  466. if (!('props' in result)) {
  467. throw new Error('invalid getSSP result');
  468. }
  469. const props: Props = result.props as Props;
  470. if (props.redirectDestination != null) {
  471. return {
  472. redirect: {
  473. permanent: false,
  474. destination: props.redirectDestination,
  475. },
  476. };
  477. }
  478. if (user != null) {
  479. props.currentUser = user.toObject();
  480. }
  481. try {
  482. await injectPageData(context, props);
  483. }
  484. catch (err) {
  485. if (err instanceof MultiplePagesHitsError) {
  486. props.isIdenticalPathPage = true;
  487. }
  488. else {
  489. throw err;
  490. }
  491. }
  492. await injectUserUISettings(context, props);
  493. await injectRoutingInformation(context, props);
  494. injectServerConfigurations(context, props);
  495. await injectNextI18NextConfigurations(context, props, ['translation']);
  496. return {
  497. props,
  498. };
  499. };
  500. export default GrowiPage;